package dns

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"
	"fmt"
	"strings"

	"github.com/k8gb-io/k8gb/controllers/logging"
	"github.com/k8gb-io/k8gb/controllers/providers/k8gbendpoint"
	"github.com/k8gb-io/k8gb/controllers/resolver"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

const externalDNSTypeCommon = "extdns"

type ExternalDNSProvider struct {
	config  resolver.Config
	client  client.Client
	context context.Context
}

var log = logging.Logger()

func NewExternalDNS(ctx context.Context, client client.Client, config resolver.Config) *ExternalDNSProvider {
	return &ExternalDNSProvider{
		context: ctx,
		client:  client,
		config:  config,
	}
}

func (p *ExternalDNSProvider) CreateZoneDelegation(zoneInfo *resolver.DelegationZoneInfo) error {
	log.Info().
		Str("provider", p.String()).
		Msg("Creating/Updating DNSEndpoint CR")
	// design break for testability - should be passed via constructor
	// consider move this into provider
	dze := k8gbendpoint.NewDelegationDNSEndpoint(p.context, p.client, p.config, log, *zoneInfo)
	ep, err := dze.GetDNSEndpoint()
	if err != nil {
		return fmt.Errorf("failed to create delegationDNSEndpoint %v", err)
	}
	err = dze.SaveDNSEndpoint(ep)
	if err != nil {
		return fmt.Errorf("failed to save delegationDNSEndpoint %v", err)
	}
	return nil
}

func (p *ExternalDNSProvider) Finalize(zoneInfo *resolver.DelegationZoneInfo) error {
	log.Info().Msgf("Domain %s will be deleted by removing delegation DNSEndpoint %s", zoneInfo.LoadBalancedZone, zoneInfo.GetExternalDNSEndpointName())
	return nil
}

func (p *ExternalDNSProvider) String() string {
	return strings.ToUpper(externalDNSTypeCommon)
}
